<template>
  <el-dialog
      v-model="dialogVisible"
      destroy-on-close
      title="三单匹配"
      width="600px"
      @close="handleClose"
  >
    <el-form v-loading="loading" :model="matchForm" label-width="100px">
      <el-form-item label="订单">
        <el-select v-model="matchForm.orderId" filterable placeholder="请选择订单">
          <template v-if="orderOptions.length > 0">
            <el-option
                v-for="item in orderOptions"
                :key="item.id ? item.id.toString() : ''"
                :label="item.orderNumber ? `${item.orderNumber} - ${item.supplierName || ''}` : '未知订单'"
                :value="item.id ? item.id.toString() : ''"
            ></el-option>
          </template>
          <el-option v-else disabled label="暂无可选订单" value=""></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="收货单">
        <el-select v-model="matchForm.receiptId" filterable placeholder="请选择收货单">
          <template v-if="receiptOptions.length > 0">
            <el-option
                v-for="item in receiptOptions"
                :key="item.id ? item.id.toString() : ''"
                :label="item.receiptNumber ? `${item.receiptNumber} - ${item.supplierName || ''}` : '未知收货单'"
                :value="item.id ? item.id.toString() : ''"
            ></el-option>
          </template>
          <el-option v-else disabled label="暂无可选收货单" value=""></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发票">
        <el-select v-model="matchForm.invoiceId" filterable placeholder="请选择发票">
          <template v-if="invoiceOptions.length > 0">
            <el-option
                v-for="item in invoiceOptions"
                :key="item.id ? item.id.toString() : ''"
                :label="item.invoiceNumber ? `${item.invoiceNumber} - ${item.supplierName || ''}` : '未知发票'"
                :value="item.id ? item.id.toString() : ''"
            ></el-option>
          </template>
          <el-option v-else disabled label="暂无可选发票" value=""></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="showDifferenceReason" label="差异原因">
        <el-input v-model="matchForm.differenceReason" :rows="2" placeholder="请输入差异原因"
                  type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="matchForm.remark" :rows="2" placeholder="请输入备注信息" type="textarea"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :loading="submitLoading" type="primary" @click="confirmMatch">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {computed, defineEmits, defineProps, reactive, ref, watch} from 'vue';
import {ElMessage} from 'element-plus';
import {MatchService} from '@/api/match';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  // 预选的订单ID，用于从订单页面进入匹配
  preSelectedOrderId: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['update:visible', 'close', 'success']);

const dialogVisible = ref(props.visible);
const loading = ref(false);
const submitLoading = ref(false);

// 匹配表单
const matchForm = reactive({
  orderId: '',
  receiptId: '',
  invoiceId: '',
  differenceReason: '',
  remark: ''
});

// 选项数据
const orderOptions = ref<any[]>([]);
const receiptOptions = ref<any[]>([]);
const invoiceOptions = ref<any[]>([]);

// 是否显示差异原因输入框
const showDifferenceReason = computed(() => {
  // 当三个单据都选择了，才检查是否需要显示差异原因
  if (matchForm.orderId && matchForm.receiptId && matchForm.invoiceId) {
    const selectedOrder = orderOptions.value.find(item => item.id === matchForm.orderId);
    const selectedReceipt = receiptOptions.value.find(item => item.id === matchForm.receiptId);
    const selectedInvoice = invoiceOptions.value.find(item => item.id === matchForm.invoiceId);

    if (selectedOrder && selectedReceipt && selectedInvoice) {
      const orderAmount = Number(selectedOrder.totalAmount || 0);
      const receiptAmount = Number(selectedReceipt.totalAmount || 0);
      const invoiceAmount = Number(selectedInvoice.totalAmount || 0);

      // 如果三个金额不完全相等，则显示差异原因输入框
      return !(orderAmount === receiptAmount && receiptAmount === invoiceAmount);
    }
  }
  return false;
});

// 监听visible属性变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal;
  if (newVal) {
    resetForm();
    loadOptions();

    // 如果有预选的订单ID，则设置并加载对应的收货单和发票
    if (props.preSelectedOrderId) {
      matchForm.orderId = props.preSelectedOrderId;
      loadCandidates();
    }
  }
});

// 监听dialogVisible变化，同步到父组件
watch(() => dialogVisible.value, (newVal) => {
  emit('update:visible', newVal);
  if (!newVal) {
    emit('close');
  }
});

// 重置表单
const resetForm = () => {
  matchForm.orderId = props.preSelectedOrderId || '';
  matchForm.receiptId = '';
  matchForm.invoiceId = '';
  matchForm.differenceReason = '';
  matchForm.remark = '';
};

// 加载选项数据
const loadOptions = async () => {
  loading.value = true;
  try {
    // 加载可匹配的订单
    const orderRes = await MatchService.getAvailableOrders({
      pageNum: 1,
      pageSize: 100
    });
    if (orderRes.code === 200) {
      orderOptions.value = orderRes.data.records || [];
    } else {
      ElMessage.error(orderRes.message || '获取可匹配订单失败');
    }

    // 如果没有预选订单，则同时加载收货单和发票
    if (!props.preSelectedOrderId) {
      // 这里可以根据需要实现加载所有可匹配的收货单和发票
      // 或者等用户选择了订单后再加载对应的收货单和发票
      receiptOptions.value = [];
      invoiceOptions.value = [];
    }
  } catch (error) {
    console.error('加载匹配选项失败', error);
    ElMessage.error('加载匹配选项失败');
  } finally {
    loading.value = false;
  }
};

// 监听订单选择变化，加载匹配候选项
watch(() => matchForm.orderId, (newVal) => {
  if (newVal) {
    loadCandidates();
  } else {
    receiptOptions.value = [];
    invoiceOptions.value = [];
  }
});

// 加载匹配候选项
const loadCandidates = async () => {
  if (!matchForm.orderId) return;

  loading.value = true;
  try {
    const res = await MatchService.getMatchCandidates(matchForm.orderId);
    if (res.code === 200) {
      receiptOptions.value = res.data.receipts || [];
      invoiceOptions.value = res.data.invoices || [];

      // 如果只有一个选项，则自动选择
      if (receiptOptions.value.length === 1) {
        matchForm.receiptId = receiptOptions.value[0].id;
      }
      if (invoiceOptions.value.length === 1) {
        matchForm.invoiceId = invoiceOptions.value[0].id;
      }
    } else {
      ElMessage.error(res.message || '获取匹配候选项失败');
    }
  } catch (error) {
    console.error('获取匹配候选项失败', error);
    ElMessage.error('获取匹配候选项失败');
  } finally {
    loading.value = false;
  }
};

// 确认匹配
const confirmMatch = async () => {
  // 表单验证
  if (!matchForm.orderId) {
    ElMessage.warning('请选择订单');
    return;
  }
  if (!matchForm.receiptId) {
    ElMessage.warning('请选择收货单');
    return;
  }
  if (!matchForm.invoiceId) {
    ElMessage.warning('请选择发票');
    return;
  }
  if (showDifferenceReason.value && !matchForm.differenceReason) {
    ElMessage.warning('存在金额差异，请填写差异原因');
    return;
  }

  submitLoading.value = true;
  try {
    const res = await MatchService.createMatch(
        matchForm.orderId,
        matchForm.receiptId,
        matchForm.invoiceId,
        matchForm.differenceReason,
        matchForm.remark
    );

    if (res.code === 200) {
      ElMessage.success('匹配成功');
      dialogVisible.value = false;
      emit('success', res.data);
    } else {
      ElMessage.error(res.message || '匹配失败');
    }
  } catch (error) {
    console.error('匹配失败', error);
    ElMessage.error('匹配失败');
  } finally {
    submitLoading.value = false;
  }
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 